package com.edu.hre.struts.action.pim;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.edu.hre.common.utils.BeanFinder;
import com.edu.hre.common.utils.ComboBoxInit;
import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.common.utils.RequestUtils;
import com.edu.hre.common.utils.StringConstants;
import com.edu.hre.db.pojo.HreEmpBasicsalary;
import com.edu.hre.db.pojo.HrePayGrade;
import com.edu.hre.db.pojo.HreUser;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.db.utils.Compare;
import com.edu.hre.struts.form.pim.EmpSalaryUpdateForm;

public class EmpSalaryUpdateAction extends DispatchAction{
	
	private static final Logger logger = Logger.getLogger(EmpSalaryUpdateAction.class);
	private static final BaseService baseService = BeanFinder.getBean(BaseService.BEAN_NAME, BaseService.class);
	private final String ACTION_NAME = "empSalaryUpdate";
	
	public ActionForward add(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		CommonUtils.println(CommonUtils.getSourceCodeLocation());

		EmpSalaryUpdateForm beanForm = (EmpSalaryUpdateForm) form;
		beanForm.setIsAddNew(true);

		if(request.getParameter(StringConstants.BTN_ADD) == null){
			
			int empNum = CommonUtils.getIntParameter("emp_num", request);
			beanForm.setEmpNumber(empNum);

			beanForm.setMessage(StringConstants.BLANK);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}
		
		EmployeeListAction.setAttributesForRequest(beanForm.getEmpNumber(), request);
		
		String message = validateForm(beanForm);
		if(!StringUtils.isBlank(message)){
			beanForm.setMessage(message);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}

		double amount = verifyAmount(beanForm.getAmount());
		
		HreEmpBasicsalary tmp = new HreEmpBasicsalary();
		tmp.setEmpNumber(beanForm.getEmpNumber());

		tmp.setSalGrdCode(beanForm.getPayGrade());
		tmp.setSalaryComponent(CommonUtils.normalizeString(beanForm.getName()));
		tmp.setPayperiodCode(CommonUtils.normalizeString(beanForm.getPayFrequency()));
		tmp.setEbsalBasicSalary(amount);
		tmp.setComments(CommonUtils.normalizeString(beanForm.getComment()));
		tmp.setDateCreated(new Date());
		tmp.setDateModified(new Date());

		boolean status = baseService.saveOrUpdate(tmp);
		if (!status) {
			beanForm.setMessage(StringConstants.INSERT_FAILURE_MESSAGE);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}

		response.getWriter().write(StringConstants.POP_UP_CLOSE_SCRIPT);
		return null;
	}

	public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		CommonUtils.println(CommonUtils.getSourceCodeLocation());
		EmpSalaryUpdateForm beanForm = (EmpSalaryUpdateForm) form;
		beanForm.setIsAddNew(false);
		
		if(request.getParameter(StringConstants.BTN_EDIT) == null){
			
			int id = CommonUtils.getIntParameter("id", request);
			HreEmpBasicsalary tmp = baseService.getFirstPojo("id", Compare.EQUAL, id, null, null, 0, HreEmpBasicsalary.class);
			
			if (tmp == null) {
				beanForm.setMessage(StringConstants.BLANK);
				initFormBean(beanForm);
				return mapping.findForward(ACTION_NAME);
			}
			
			beanForm.setId(id);
			beanForm.setEmpNumber(tmp.getEmpNumber());

			beanForm.setName(CommonUtils.normalizeString(tmp.getSalaryComponent()));
			beanForm.setPayGrade(tmp.getSalGrdCode());
			beanForm.setPayFrequency(CommonUtils.normalizeString(tmp.getPayperiodCode()));
			beanForm.setAmount(tmp.getEbsalBasicSalary() + StringConstants.BLANK);
			beanForm.setComment(CommonUtils.normalizeString(tmp.getComments()));

			beanForm.setMessage(StringConstants.BLANK);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}
		
		EmployeeListAction.setAttributesForRequest(beanForm.getEmpNumber(), request);
		
		String message = validateForm(beanForm);
		if(!StringUtils.isBlank(message)){
			beanForm.setMessage(message);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}

		double amount = verifyAmount(beanForm.getAmount());

		HreEmpBasicsalary tmp = baseService.getFirstPojo("id", Compare.EQUAL, beanForm.getId(), null, null, 0, HreEmpBasicsalary.class);
		if (tmp == null) {
			beanForm.setMessage(StringConstants.BLANK);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}

		tmp.setSalGrdCode(beanForm.getPayGrade());
		tmp.setSalaryComponent(CommonUtils.normalizeString(beanForm.getName()));
		tmp.setPayperiodCode(CommonUtils.normalizeString(beanForm.getPayFrequency()));
		tmp.setEbsalBasicSalary(amount);
		tmp.setComments(CommonUtils.normalizeString(beanForm.getComment()));
		tmp.setDateModified(new Date());

		boolean status = baseService.saveOrUpdate(tmp);
		if (!status) {
			beanForm.setMessage(StringConstants.UPDATE_FAILURE_MESSAGE);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}

		response.getWriter().write(
				 "<script language=\"javascript\">\n" +
						" parent.dw.close();" + 
						 " var param = parent.document.createElement('input'); " +
						 " param.type = 'hidden'; " +
						 " param.name = 'id'; " +
						 " param.value = " + tmp.getEmpNumber() +  ";" +
						 " parent.document.forms[0].appendChild(param);" +
						" parent.document.forms[0].submit(); \n" +
				 "</script>");
		return null;
	}

	private double verifyAmount (String amount) {
		try {
			return Double.parseDouble(amount);
		} catch (Exception e) {
			return -1;
		}
	}

	private void initFormBean (EmpSalaryUpdateForm beanForm) {

		beanForm.setAllPayFrequencies(ComboBoxInit.getAllPayFrequencies(false));
		beanForm.setAllPayGrades(ComboBoxInit.getAllPayGrades(false));
	}
	
	private boolean validateRange (double amount, int id, String[] announcedRange) {
		
		HrePayGrade grade = baseService.getFirstPojo("id", Compare.EQUAL, id, null, null, -1, HrePayGrade.class);
		if (grade == null) {
			announcedRange[0] = "NA";
			announcedRange[1] = "NA";
			return false;
		}

		if (amount <= grade.getMaxSalary() && amount >= grade.getMinSalary()) {
			return true;
		}

		announcedRange[0] = grade.getMinSalary() + " " + grade.getCurrencyId();
		announcedRange[1] = grade.getMaxSalary() + " " + grade.getCurrencyId();
		return false;
	}
	
	private String validateForm (EmpSalaryUpdateForm beanForm) {
		
		if(StringUtils.isBlank(CommonUtils.normalizeString(beanForm.getName()))) {
			return "Component name cannot be blank!";
		}
		
		if(StringUtils.isBlank(CommonUtils.normalizeString(beanForm.getAmount()))) {
			return "Component amount is a required field!";
		}
		
		double amount = verifyAmount(beanForm.getAmount());
		
		if (amount <= 0) {
			return "Component amount must be a positive real number!";
		}
		
		String[] announcedRange = new String[2];
		boolean isInRange = validateRange(amount, beanForm.getPayGrade(), announcedRange);
		if (!isInRange) {
			return "Amount must be in the range from " + announcedRange[0] + " to " + announcedRange[1] + ".";
		}

		return StringConstants.BLANK;
	}
}
